package com.sq.partner.manager.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.sq.partner.manager.common.DictCache;
import com.sq.partner.manager.dao.INlifeProdDao;
import com.sq.partner.manager.dao.RuleAgentConfigDao;
import com.sq.partner.manager.dao.RuleConfigerDao;
import com.sq.partner.manager.dao.SchoolConfigDao;
import com.sq.partner.manager.dao.impl.NlifePlanDaoImpl;
import com.sq.partner.manager.mybatis.model.DictDto;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.RuleDefinition;
import com.sq.partner.manager.mybatis.model.RuleTemplateRale;
import com.sq.partner.manager.service.RuleConfigerService;
import com.sq.partner.manager.util.JsonUtils;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.StrUtil;
@Service
public class RuleConfigerServiceImpl implements
		RuleConfigerService {
	@Resource
	RuleConfigerDao ruleConfigerDao;
	@Resource
	RuleAgentConfigDao rleAgentConfigDao;
	@Resource
	INlifeProdDao NlifeProdDao;
	@Resource
	SchoolConfigDao schoolConfigDao;
	@Resource
	NlifePlanDaoImpl nlifePlanDaoImpl;
	
	@Override
	public Page<Map<String, Object>> queryPlanPageByCriteria(Page<Map<String, Object>> page,
			GatewayUser user) throws Exception {
		return ruleConfigerDao.queryPlanPageByCriteria(page, user);
	}
	@Override
	public Map<String, Object> queryTemplate(String riskMain, String prodType,String planCode)
			throws Exception {
		Map<String, Object> map=new HashMap<String, Object>();
		if(StrUtil.isEmpty(riskMain)){
			riskMain=null;
		}
		map.put("riskMain", riskMain);
		map.put("prodType", prodType);
		List<Map<String, Object>> templates=ruleConfigerDao.queryTemplate(map);
		map.put("planCode", planCode);
		String maxOccup =ruleConfigerDao.queryMaxOccup(map);
		if(templates!=null){
			for (int i = 0; i < templates.size(); i++) {
				if("select".equals(templates.get(i).get("ATTRIIDBUTE_TYPE"))){
					List<DictDto>dics=DictCache.getDict("rule_template_"+templates.get(i).get("ATTRIIDBUTE_ID"));
					templates.get(i).put("DICT_NAME", dics);
				}
				if("select_work".equals(templates.get(i).get("ATTRIIDBUTE_TYPE"))){
					if(maxOccup==null){
						List<DictDto>dics=DictCache.getDict("OccupationCode1");
						templates.get(i).put("WORK_TYPE", dics);
					}else{
						String sql="select * from t_gateway_dict where code_desc like '%职业类别%' and  other_code <= '"+maxOccup+"'";
						List<DictDto> dics = DictCache.getDict1("OccupationCode1", sql);
						templates.get(i).put("WORK_TYPE", dics);
					}
				}
				if("select_school".equals(templates.get(i).get("ATTRIIDBUTE_TYPE"))){
					String sql="select * from t_gateway_dict t where length(t.code)=9 and t.code_type = 'school_config'";
					List<DictDto> dicts = DictCache.getDict1("school_config", sql);
					templates.get(i).put("SCHOOL_CONFIG", dicts==null?"":dicts);
				}
			}
		}
		String specTypeInfo = NlifeProdDao.getSpecTypeInNlifeProd(planCode);
		map.put("specTypeInfo",specTypeInfo);
		map.put("templates", templates);
		return map;
	}
	@Override
	public Page saveTemplateList(String ruleTemplate, String ruleName,
			String planCode,String partnerNo) throws Exception { 
		Page page=new Page();
		List<RuleTemplateRale> relas=new ArrayList<RuleTemplateRale>();
		String ruleId = "";
		RuleDefinition definition=new RuleDefinition();
		definition.setInsertTime(new Date());
		ruleId= ruleConfigerDao.queryNextRuleId("RULE-");
		if(StrUtil.isEmpty(ruleId)){
			ruleId="RULE-0001";
		}else{
			String zero="";
			if(ruleId.length()<4){
				for (int i = 0; i < 4-ruleId.length(); i++) {
					zero+="0";
				}
			}
			ruleId="RULE-"+zero+ruleId;
		}
		definition.setId(ruleId);
		definition.setRuleName(ruleName);
		definition.setPlanNo(planCode);
		definition.setPartnerNo(partnerNo);
		boolean result=ruleConfigerDao.saveRuleDefinition(definition);
		if(result){
			/**解析元素列表*/
			List<Map<String,Object>> list = JsonUtils.parseJson(ruleTemplate, ArrayList.class);	
			for (Map<String, Object> map : list) {
				RuleTemplateRale rela=new RuleTemplateRale();
				rela.setRuleId(definition.getId()+"");
				rela.setAttriidbuteId((String) map.get("attrid"));
				rela.setBringVal((String)map.get("attrVal"));
				rela.setIsDisabled((String)map.get("isDis"));
				rela.setAttriidbuteIdName((String)map.get("attrType"));
				rela.setIsRequired((String)map.get("isReq"));
				relas.add(rela);
			}
			boolean result1=ruleConfigerDao.insertRuleTemplateRaleList(relas);
			if(result1){
				page.setMessage("操作成功");
				page.setResult("success");
			}else{
				page.setMessage("操作出错");
				page.setResult("error");
			}
		}else{
			page.setMessage("操作出错");
			page.setResult("error");
		}
		return page;
	}
	@Override
	public Page<RuleDefinition> queryDefinitionPage(Page<RuleDefinition> page)
			throws Exception {
		return ruleConfigerDao.queryDefinitionPage(page);
	}
	@Override
	public Map<String, Object> editDefinition(String id)
			throws Exception {
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("id", id);
		List<Map<String, Object>>templates= ruleConfigerDao.queryEditTemplate(map);
		String maxOccup =ruleConfigerDao.queryMaxOccup(map);
		if(templates!=null){
			for (int i = 0; i < templates.size(); i++) {
				if("select".equals(templates.get(i).get("ATTRIIDBUTE_TYPE"))){
					List<DictDto>dics=DictCache.getDict("rule_template_"+templates.get(i).get("ATTRIIDBUTE_ID"));
					templates.get(i).put("DICT_NAME", dics);
				}
				if("select_work".equals(templates.get(i).get("ATTRIIDBUTE_TYPE"))){
					if(maxOccup==null){
						List<DictDto>dics=DictCache.getDict("OccupationCode1");
						templates.get(i).put("WORK_TYPE", dics);
					}else{
						String sql="select * from t_gateway_dict where code_desc like '%职业类别%' and  other_code <= '"+maxOccup+"'";
						List<DictDto> dics = DictCache.getDict1("OccupationCode1", sql);
						templates.get(i).put("WORK_TYPE", dics);
					}
				}
				if("select_school".equals(templates.get(i).get("ATTRIIDBUTE_TYPE"))){
					String sql1="select * from t_gateway_dict t where length(t.code)=9 and t.code_type = 'school_config'";
					List<DictDto> schoolDicts = DictCache.getDict1("school_config", sql1);
					templates.get(i).put("SCHOOL_CONFIG", schoolDicts==null?"":schoolDicts);
					if (templates.get(i).get("BRING_VAL")!=null) {
						String[] arr = templates.get(i).get("BRING_VAL").toString().split(",");
						if (arr.length==2) {
							Map<String, Object> paramMap1 = new HashMap<String, Object>();
							paramMap1.put("code", arr[1]);
							List<Map<String, Object>> gradeDicts = schoolConfigDao.querySchoolConfigSelect(paramMap1);
							templates.get(i).put("SCHOOLGRADE_CONFIG", gradeDicts);
						}else if(arr.length==3){
							Map<String, Object> paramMap1 = new HashMap<String, Object>();
							paramMap1.put("code", arr[1]);
							List<Map<String, Object>> gradeDicts = schoolConfigDao.querySchoolConfigSelect(paramMap1);
							templates.get(i).put("SCHOOLGRADE_CONFIG", gradeDicts);
							for (Map<String, Object> gradeMap : gradeDicts) {
								if (gradeMap.get("CODE_DESC").toString().contains(arr[2])) {
									String className = gradeMap.get("CODE_DESC").toString();
									String[] classArr = className.split(",");
									templates.get(i).put("SCHOOLCLASS_CONFIG", classArr);
								}
							}
						}
					}
				}
				if(templates.get(i).get("BRING_VAL")==null){
					templates.get(i).put("BRING_VAL", "");
				}
			}
		}
		Map<String, Object>ruleMap=ruleConfigerDao.queryDefinitionById(id);
		
		String specTypeInfo = NlifeProdDao.getSpecTypeInNlifeProd((String)(templates.get(0).get("PLAN_NO")));
		map.put("specTypeInfo",specTypeInfo);
		map.put("templates", templates);
		map.putAll(ruleMap);
		return map;
	}
	@Override
	public Page editTemplateList(String ruleTemplate, String ruleName,
			String planCode, String partnerNo, String ruleId) throws Exception {
		Page page=new Page();
		List<RuleTemplateRale> relas=new ArrayList<RuleTemplateRale>();
		RuleDefinition definition=new RuleDefinition(); 
		definition.setInsertTime(new Date());
		definition.setRuleName(ruleName);
		definition.setPlanNo(planCode);
		definition.setPartnerNo(partnerNo);
		definition.setId(ruleId);
		boolean result=ruleConfigerDao.editRuleDefinition(definition);
		if(result){
			/**解析元素列表*/
			List<Map<String,Object>> list = JsonUtils.parseJson(ruleTemplate, ArrayList.class);	
			for (Map<String, Object> map : list) {
				RuleTemplateRale rela=new RuleTemplateRale();
				rela.setRuleId(definition.getId()+"");
				rela.setAttriidbuteId((String) map.get("attrid"));
				rela.setBringVal((String)map.get("attrVal"));
				rela.setIsDisabled((String)map.get("isDis"));
				rela.setAttriidbuteIdName((String)map.get("attrType"));
				rela.setIsRequired((String)map.get("isReq"));
				relas.add(rela);
			}
			/**删除原信息*/
			if(ruleConfigerDao.deleteTemplatByRuleId(ruleId)){
				boolean result1=ruleConfigerDao.insertRuleTemplateRaleList(relas);
				if(result1){
					page.setMessage("操作成功");
					page.setResult("success");
				}else{
					page.setMessage("操作出错");
					page.setResult("error");
				}	
			}else{
				page.setMessage("操作出错");
				page.setResult("error");
			};
			
		}else{
			page.setMessage("操作出错");
			page.setResult("error");
		}
		return page;
	}
	@Override
	public Page deleteRuleByid(String id) throws Exception {
		Page page=new Page();
		/**查询是否已经关联了二维码信息*/
		List<Map<String, Object>> list=rleAgentConfigDao.queryRuleAgentByRuleId(id);
		if(list!=null&&list.size()>0){
			page.setMessage("已关联录单二维码，无法删除");
			page.setResult("error");
			return page;
		}
		boolean result ;
		if(ruleConfigerDao.deleteRuleByRuleId(id)){
			result=ruleConfigerDao.deleteTemplatByRuleId(id);
		}else{
			result=false;
		}
		if(result){
			page.setMessage("操作成功");
			page.setResult("success");
		}else{
			page.setMessage("操作失败");
			page.setResult("error");
		}
		return page;
	}
}
